package com.tengits.mqttmonitor.rnlibs.rs;

import android.util.Log;

import androidx.annotation.Nullable;

import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.modules.core.DeviceEventManagerModule;

import java.io.IOException;

public abstract class SerialPortBase{
    public static String DataReceivedEvent = "serial_event";
    private static final char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray();

    protected final ReactContext mReactContext;

    protected String key;
    public int baudRate = 9600;
    public int dataBits = 8;
    public int parity = 0;
    public int stopBits = 1;
    protected int refCount = 1;

    public SerialPortBase(ReactContext reactContext, final String key, int baudRate, int parity, int dataBits, int stopBits) {
        this.mReactContext = reactContext;
        this.key = key;
        this.baudRate = baudRate;
        this.parity = parity;
        this.dataBits = dataBits;
        this.stopBits = stopBits;
    }

    public String getKey() {
        return key;
    }

    protected void sendEvent(final String eventName, @Nullable final WritableMap event) {
        if(!mReactContext.hasActiveReactInstance()) {
            return;
        }
        // Log.e("usb", "sendEvent start");
        mReactContext
                .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
                .emit(eventName, event);
        // Log.e("usb", "sendEvent end");
    }

    public static byte[] hexStringToByteArray(String s) {
        int len = s.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                    + Character.digit(s.charAt(i + 1), 16));
        }
        return data;
    }

    public static String bytesToHex(byte[] bytes) {
        char[] hexChars = new char[bytes.length * 2];
        for (int j = 0; j < bytes.length; j++) {
            int v = bytes[j] & 0xFF;
            hexChars[j * 2] = HEX_ARRAY[v >>> 4];
            hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F];
        }
        return new String(hexChars);
    }

    public void addRef() {
        this.refCount += 1;
    }

    public int release() {
        this.refCount -= 1;
        return this.refCount;
    }

    public abstract void writeHex(String buffer) throws IOException;
    public abstract boolean close(boolean isForce);
    public abstract boolean isRunning();
}
